//
//  UIImageView+SGExtension.swift
//  Swift-Codedase
//
//  Created by xyanl on 2023/9/5.
//

import UIKit

extension UIImageView {
    
    /// 初始化 git imageView
    /// - Parameter gifPath: git 的路径
    convenience init?(_ gifPath: String) {
        if gifPath.isEmpty {
            return nil
        }
        
        guard let data = NSData(contentsOfFile: gifPath) else {
            return nil
        }
        
        guard let imgSource: CGImageSource = CGImageSourceCreateWithData(data as CFData, nil) else {
            return nil
        }
        
        // 获取组成gif的图片总数量（gif都是由很多张图片组成）
        let imageCount = CGImageSourceGetCount(imgSource)
        
        var images = [UIImage]()
        var totalDuration : TimeInterval = 0
        var size = CGSizeZero
        for i in 0...imageCount {
            guard let cgImage = CGImageSourceCreateImageAtIndex(imgSource, i, nil) else {
                continue
            }
            guard let properties : NSDictionary = CGImageSourceCopyPropertiesAtIndex(imgSource, i, nil) else {
                continue
            }
            // 获取单张图片的播放时长
            guard let gifDic = properties[kCGImagePropertyGIFDictionary] as? NSDictionary else {
                continue
            }
            
            guard let duration = gifDic[kCGImagePropertyGIFDelayTime] as? NSNumber else {
                continue
            }
            // 将播放时间累加
            totalDuration += duration.doubleValue
            // 获取到所有的image
            let image = UIImage(cgImage: cgImage)
            images.append(image)
            size = image.size
        }
        
        self.init(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        animationImages = images
        animationDuration = totalDuration
        animationRepeatCount = 0
        startAnimating()
    }
    
}
